package com.lxl.commons.filter;


import com.lxl.commons.contants.Contants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录权限验证过滤器
 * @author 北上寻海
 */

public class LoginFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        /**
         * 目前所有路径都拦截了
         * 以下路径是不能拦截的
         *     index.jsp(登录页面)
         *     /welcome(判断是否有七天免登录的cookie页面)
         *     已经登录了，在session域中存了登录信息了
         */
        String uri = request.getRequestURI();
        //拿当前的session：默认是true，表示如果没有就新建一个；false是没有就返回null
        HttpSession session = request.getSession(false);
        String loginPage = "/login";
        String welcomePage ="/welcome";
        String indexPage = "/index.jsp";
        String verifyCodePage ="/verifyCode";
        String jsPath = "/js/jquery-3.4.1.js";
        boolean result =  uri.contains(loginPage)
                ||uri.contains(welcomePage)
                ||uri.contains(indexPage)
                ||uri.contains(verifyCodePage)
                ||uri.contains(jsPath)
                ||(session!=null&&session.getAttribute(Contants.SESSION_USER)!=null);
        if(result){
            chain.doFilter(request, response);
        }
        else {
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {

    }

}
